package org.example;

public class Test4 {
    //leetcode 105 从前序和中序遍历序列构造二叉树 https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
    int i;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildChildTree(preorder,inorder,0,inorder.length - 1);
    }

    public TreeNode buildChildTree(int[] preorder, int[] inorder, int left, int right) {
        if (left > right) return null;
        TreeNode root = new TreeNode(preorder[i]);
        int pivot = findIndex(inorder,preorder[i++],left,right);
        root.left = buildChildTree(preorder,inorder,left,pivot - 1);
        root.right = buildChildTree(preorder,inorder, pivot + 1,right);
        return root;
    }

    public int findIndex(int[] inorder, int target, int left, int right) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) return i;
        }
        return -1;
    }
}
